package com.lz.yz.homepage.controller;

import com.lz.yz.base.entity.ReturnValue;
import com.lz.yz.base.util.Constant;
import com.lz.yz.home.entity.Banner;
import com.lz.yz.home.param.HomePageParam;
import com.lz.yz.homepage.service.BannerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * Created by Administrator on 2017/5/5.
 */
@RestController
public class BannerController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    BannerService bannerService;

    //编辑查询
    @GetMapping("/banner/getOne/{id}")
    public ReturnValue getOne(@PathVariable Integer id){
        try {
            Banner result = bannerService.getOne(id);
            return ReturnValue.generateTrueReturnValue(result);
        } catch (Exception e) {
            logger.error("操作失败", e);
            return ReturnValue.generateFalseReturnValue("操作失败!");
        }
    }

    //更新
    @PutMapping("/banner/update/{id}")
    public ReturnValue update(@RequestBody Banner model){
        try {
            bannerService.update(model);
            return ReturnValue.generateTrueReturnValue("");
        } catch (Exception e) {
            logger.error("操作失败", e);
            return ReturnValue.generateFalseReturnValue("操作失败!");
        }
    }

    //新增
    @PostMapping("/banner/save")
    public ReturnValue save(@RequestBody Banner model){
        try {
            bannerService.addBanner(model);
            return ReturnValue.generateTrueReturnValue("操作成功");
        } catch (Exception e) {
            logger.error("操作失败", e);
            return ReturnValue.generateFalseReturnValue("操作失败!");
        }
    }


    //删除
    @DeleteMapping("/banner/delete/{id}")
    public ReturnValue delete(@PathVariable Integer id){
        try {
            bannerService.delete(id);
            return ReturnValue.generateTrueReturnValue("删除成功");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ReturnValue.generateFalseReturnValue("删除失败!");
        }
    }

    //查询list
    @GetMapping("/banner")
    public ReturnValue getList(String search, @RequestParam Optional<Integer> pageSize, @RequestParam Optional<Integer> page){
        try {
            HomePageParam param = new HomePageParam(pageSize.orElse(Constant.DEFAULT_PAGE_SIZE),page.orElse(Constant.DEFAULT_PAGE));
            param.setSearch(search);
            return bannerService.getList(param);
        } catch (Exception e) {
            logger.error("查询失败", e);
            return ReturnValue.generateFalseReturnValue("查询失败!");
        }
    }
}
